<?php

namespace GroupBuying;

use C\L\AdmController;
use C\M\GroupBuyingUserOrder;
use C\M\User;

class UserOrderController extends AdmController
{
  /**
   * 列表、搜索接口
   **/
    public function indexAction()
    {
        $currentPage = $this->request->getQuery('page', 'int', 1);
        $perPage     = $this->request->getQuery('per_page', 'int', 20);
        $state       = $this->request->getQuery('state', 'string', null);
        $orderSn     = $this->request->getQuery('order_sn', 'string', null);
        $orderState  = $this->request->getQuery('order_state', 'string', null);
        $goodsTitle  = $this->request->getQuery('goods_title', 'string', null);
        $type        = $this->request->getQuery('type', 'string', 'real');
        $userMobile  = $this->request->getQuery('user', 'string', null);

        $builder = $this->modelsManager->createBuilder()
        ->columns(['group_buying_user_order.*', 'group_buying_order.sn', 'group_buying_order.state'])
        ->from(['group_buying_user_order' => 'C\M\GroupBuyingUserOrder'])
        ->join(
            'C\M\GroupBuyingOrder',
            'group_buying_order.id = group_buying_user_order.group_buying_order_id',
            'group_buying_order'
        )
        ->orderBy('group_buying_user_order.id DESC');

        switch ($type) {
            case 'real':
                $builder = $builder->andWhere('group_buying_user_order.user_id != :user_id:', ['user_id' => 0]);
                break;
            case 'generated':
                $builder = $builder->andWhere('group_buying_user_order.user_id = :user_id:', ['user_id' => 0]);
                break;
            default:
                break;
        }

        if ($state) {
            $builder = $builder->andWhere('group_buying_user_order.state = :state:', ['state' => $state]);
        }
        if ($orderSn) {
            $builder = $builder->andWhere('group_buying_order.sn LIKE :sn:', ['sn' => '%' . $orderSn . '%']);
        }
        if ($orderState) {
            $builder = $builder->andWhere('group_buying_order.state = :order_state:', ['order_state' => $orderState]);
        }
        if ($goodsTitle) {
            $builder = $builder->andWhere(
                "JSON_EXTRACT(group_buying_user_order.other_info, '$.goods.title') LIKE :goods_title:",
                ['goods_title' => '%' . $goodsTitle . '%']
            );
        }
        if ($userMobile) {
            $user = User::findFirst("mobile = '$userMobile'");
            $builder = $builder->andWhere(
                'group_buying_user_order.user_id = :filter_user_id:',
                ['filter_user_id' => $user->uid ?? null]
            );
        }

        $pagination = $this->paginationByBuilder($builder, $currentPage, $perPage);

        $items = array_map(function ($item) {
            $data = $item->group_buying_user_order->toArray();
            $data['other_info']  = json_decode($data['other_info'], true);
            $data['order_sn']    = $item->sn;
            $data['order_state'] = $item->state;
            $data['created_at']  = date('Y-m-d H:i:s', $data['addtime']);
            return $data;
        }, $pagination['items']->toArray());

        $result = array_merge($pagination, compact('items'));

        $this->success($result);
    }

    public function shipAction()
    {
        $id           = $this->request->getPost('id', 'int', 0);
        $waybillNumber = $this->request->getPost('waybill_number', 'string', null);
        $company       = $this->request->getPost('company', 'string', null);

        $userOrder = GroupBuyingUserOrder::findFirst([
          'conditions' => 'id = :id: AND state = :state:',
          'bind'       => ['id' => $id, 'state' => 'paid'],
        ]);
        if (!$userOrder) {
            return $this->error('未找到对应资源');
        }

        try {
            $this->di['db']->begin();

            $shipResult = $this->s_shipment->ship($id, 'group_buying_user_order', $company, $waybillNumber);
            if (!$shipResult) {
                return $this->error();
            }

            $userOrder->state = 'shipped';
            $result = $userOrder->save();
            if (!$result) {
                throw new \Exception('更新拼单订单状态失败');
            }

            $this->di['db']->commit();
            $this->success();
        } catch (\Exception $e) {
            if ($this->di['db']->isUnderTransaction()) {
                $this->di['db']->rollback();
            }

            $this->error($e->getMessage());
        }
    }

    public function cancelAction()
    {
        $id = $this->request->getPost('id', 'int', 0);

        try {
            $result = $this->s_group_buying_user_order->cancel($id);

            if (!$result) {
                return $this->error();
            }
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }

        return $this->success();
    }

    public function refundAction()
    {
        $id = $this->request->getPost('id', 'int', 0);

        try {
            $result = $this->s_group_buying_user_order->refund($id);

            if (!$result) {
                return $this->error();
            }
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }

        return $this->success();
    }
}
